package com.hmall.controller;


import com.hmall.common.utils.AliyunOSSOperator;
import com.hmall.domain.po.Information;
import com.hmall.domain.po.Result;
import com.hmall.service.IInformationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
//@CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.GET,
//        RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private IInformationService informationService;

    /** 本地磁盘存储方案
    @PostMapping("/upload")
    public Result upload(String name, MultipartFile file) throws IOException {
//        uploadService.add(name,file);

        //文件的本地存储
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID().toString() + extension;

        file.transferTo(new File("D:/images/" + newFilename));
        String path = "D:/images/" + newFilename;
        uploadService.add(name,path);
        return Result.success();
    }
    */

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    /**
     * 文件上传  阿里云OSS存储方案
     */
    @PostMapping
    public Result upload(MultipartFile file) throws Exception{
        log.info("上传文件：{}",file.getOriginalFilename());
        //文件交给OSS文件管理
        String url = aliyunOSSOperator.upload(file.getBytes(),file.getOriginalFilename());
        log.info("文件上传成功，返回的url为：{}",url);
        return Result.success(url);
    }

    /**
     * 新增个人信息
     */
    @PostMapping( "/person")
    public Result saveInfornation(@RequestBody Information information){
        informationService.saveByUserId(information);
        return Result.success();
    }

    /**
     * 修改个人信息
     */
    @PutMapping
    public Result updateInformation(Information information,@RequestParam(value = "file", required = true) MultipartFile file){
        informationService.updateByUserId(information,file);
        return Result.success();
    }




}
